<template>
  <div>
    <van-nav-bar>
      <template #title>
        <h3>平度农村集体三资公开平台</h3>
      </template>
    </van-nav-bar>
    <van-cell-group>
      <van-field
        v-model="currentTown.text"
        is-link
        size="large"
        readonly
        name="picker"
        label="镇街"
        placeholder="点击选择镇街"
        @click="selectTown"
      />
      <van-popup v-model:show="showTownPicker" destroy-on-close position="bottom">
        <van-picker
          :columns="townOptions"
          @confirm="onTownConfirm"
          @cancel="showTownPicker = false"
        />
      </van-popup>

      <van-field
        v-model="currentVillage.text"
        is-link
        size="large"
        readonly
        name="picker"
        label="村庄"
        placeholder="点击选择村庄"
        @click="selectVillage"
      />
      <van-popup v-model:show="showVillagePicker" destroy-on-close position="bottom">
        <van-picker
          :columns="villageOptions"
          @confirm="onVillageConfirm"
          @cancel="showVillagePicker = false"
        />
      </van-popup>

      <van-field
        v-model="currentOrg.text"
        is-link
        size="large"
        readonly
        name="picker"
        label="经济组织"
        placeholder="点击选择经济组织"
        @click="selectOrg"
      />
      <van-popup v-model:show="showOrgPicker" destroy-on-close position="bottom">
        <van-picker
          :columns="orgOptions"
          @confirm="onOrgConfirm"
          @cancel="showOrgPicker = false"
        />
      </van-popup>

      <van-field v-model="idCard" size="large" label="身份证" placeholder="请输入身份证号" />
      <van-button type="primary" block @click="submit">提交</van-button>
    </van-cell-group>
    <van-notice-bar
      left-icon="volume-o"
      text="如遇身份证信息不存在，烦请联系当地镇街经管站上报个人信息。"
    />
  </div>
</template>
<script setup lang="ts">
import { NodeData, City } from '@/interface/home'
import { onMounted, ref } from 'vue'
import { useRouter } from 'vue-router'
import { idCardPattern } from './homeData'
import { Toast } from 'vant';
import { appApi } from '@/api'

const router = useRouter();

// 区县
const county = ref<City>({
  code: '370283',
  name: '平度市',
  pcode: '3702',
  children:[],
});

let cityData: City[] = [];

// 乡镇列表
const towns = ref<City[]>([]);
// 乡镇选择器选项
const townOptions = ref<NodeData[]>([]);
// 当前选择的乡镇
const currentTown = ref<NodeData>({
  text: '',
  value: '',
  pcode: '',
});
// 乡镇选择器是否显示
const showTownPicker = ref(false);

// 村列表
const villages = ref<City[]>([]);
// 村庄选择器选项
const villageOptions = ref<NodeData[]>([]);
// 当前选择的村庄
const currentVillage = ref<NodeData>({
  text: '',
  value: '',
  pcode: '',
});
// 村选择器是否显示
const showVillagePicker = ref(false);

// 村经济组织列表
const orgs = ref<City[]>([]);
// 组织选择器选项
const orgOptions = ref<NodeData[]>([]);
// 当前选择的村经济组织
const currentOrg = ref<NodeData>({
  text: '',
  value: '',
  pcode: '',
});
// 组织选择器是否显示
const showOrgPicker = ref(false);

// 身份证号
const idCard = ref('');


onMounted(() => {
  findOrg();
})

const findOrg = async () => {
  if(!county.value.code) {
    Toast('请先选择区县')
    return;
  }
  appApi.findOrg(county.value.code, '1').then((res: any) => {
    cityData = res;
    if(cityData.length > 0) {
      county.value = cityData[0];
    }
    if(county.value.children && county.value.children.length > 0) {
      towns.value = county.value.children;
    }
  }).catch(err => {
    Toast('获取机构失败：' + err);
  });
}

/** 打开选择乡镇 */
const selectTown = () => {
  townOptions.value = [];

  if(!towns.value) {
    Toast('请先选择区县')
    return;
  }
  const arr = towns.value.map(item => {
    return {
      text: item.name,
      value: item.code,
      pcode: item.pcode
    }
  });
  townOptions.value = arr;
  showTownPicker.value = true;
}

/** 确认选择乡镇 */
const onTownConfirm = (selectedOptions: NodeData) => {
  currentTown.value = selectedOptions;
  // 选择乡镇后，根据乡镇code查询村列表
  const selectedTown = towns.value.find(item => item.code === selectedOptions.value);
  villages.value = [];
  if(selectedTown && selectedTown.children) {
    villages.value = selectedTown.children;
  }
  showTownPicker.value = false;
}

/** 打开选择村庄 */
const selectVillage = () => {
  villageOptions.value = [];

  if(!villages.value) {
    Toast('请先选择乡镇')
    return;
  }
  const arr = villages.value.map(item => {
    return {
      text: item.name,
      value: item.code,
      pcode: item.pcode
    }
  });
  villageOptions.value = arr;
  showVillagePicker.value = true;
}

/** 确认选择村庄 */
const onVillageConfirm = (selectedOptions: NodeData) => {
  currentVillage.value = selectedOptions;
  // 选择村后，根据村code查询组织列表
  const selectedVillage = villages.value.find(item => item.code === selectedOptions.value);
  orgs.value = [];
  if(selectedVillage && selectedVillage.children) {
    orgs.value = selectedVillage.children;
  }
  showVillagePicker.value = false;
}

/** 打开选择村经济组织 */
const selectOrg = () => {
  orgOptions.value = [];

  if(!orgs.value) {
    Toast('请先选择村庄')
    return;
  }
  const arr = orgs.value.map(item => {
    return {
      text: item.name,
      value: item.code,
      pcode: item.pcode
    }
  });
  orgOptions.value = arr;
  showOrgPicker.value = true;
}

/** 确认选择村经济组织 */
const onOrgConfirm = (selectedOptions: NodeData) => {
  currentOrg.value = selectedOptions;
  showOrgPicker.value = false;
}

const submit = () => {
  if(!currentTown.value.value) {
    Toast('请先选择镇街')
    return;
  }
  if(!currentVillage.value.value) {
    Toast('请先选择村庄')
    return;
  }
  if(!currentOrg.value.value) {
    Toast('请先选择村经济组织')
    return;
  }
  // 验证身份证格式
  if (!idCardPattern.test(idCard.value)) {
    Toast('身份证格式不正确');
    return;
  }
  appApi.permissionCheck(idCard.value,currentOrg.value.value).then(() => {
    sessionStorage.setItem('loginUser', JSON.stringify({
      idCard: idCard.value,
      orgCode: currentOrg.value.value
    }));
    router.push({
      path: '/info',
    })
  }).catch(err => {
    Toast(err);
  });
}
</script>

<style lang="less" scoped>

</style>
